import postLoginByAccount, { getRoleMenus, getUserById } from '@/service/login/login'
import { defineStore } from 'pinia'
import router from '@/router'
import { localCache } from '@/utils/cache'
import { TOKEN, USER_INFO, USER_MENUS } from '@/utils/token'
import type { IUserInfo, IUserMenus } from '@/types/login/login'
import { mapMenus } from '@/utils/mapmenu'
import useMainStore from '../main/main'
import { mapPermissions } from '@/utils/mapPermissions'
import useDashboardStore from '../dashboard/dashboard'

const useLoginStore = defineStore('login', {
  state: () => ({
    token: '',
    userInfo: {} as IUserInfo,
    userMenus: [] as IUserMenus[],
    permissionList: [] as any[]
  }),
  actions: {
    // 请求登录
    async postLoginAction(name: string, password: string) {
      // 1.获取用户信息
      const loginRes = await postLoginByAccount(name, password)
      const { id, token } = loginRes.data

      // 2.存储登录信息
      this.token = token
      localCache.setCache(TOKEN, token)

      // 3.根据用户的id获取角色信息
      const userInfoRes = await getUserById(id)
      this.userInfo = userInfoRes.data

      // 4.根据用户的id(role)请求菜单信息
      const userMenus = await getRoleMenus(this.userInfo.role.id)
      this.userMenus = userMenus.data

      // 5.本地存储用户的角色信息及菜单信息
      localCache.setCache(USER_INFO, userInfoRes.data)
      localCache.setCache(USER_MENUS, userMenus.data)

      // 用户按钮权限判断
      const permissionList = mapPermissions(userMenus.data)
      this.permissionList = permissionList

      // 6.根据菜单信息动态添加路由
      const routes = mapMenus(userMenus.data)
      routes.forEach((route) => router.addRoute('main', route))

      // 3.跳转页面
      router.push('/main')
    },

    // 重新加载数据
    loadDataAction() {
      const token = localCache.getCache(TOKEN)
      const userInfo = localCache.getCache(USER_INFO)
      const userMenus = localCache.getCache(USER_MENUS)

      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 用户按钮权限判断
        const permissionList = mapPermissions(userMenus)
        this.permissionList = permissionList

        // 1.动态添加路由
        const routes = mapMenus(userMenus)
        routes.forEach((route) => router.addRoute('main', route))

        // 2.获取角色及部门数据
        const mainStore = useMainStore()
        mainStore.getEntireDepartmentsAction()
        mainStore.getEntireRolesAction()
        mainStore.getMenuListAction()

        // // 3.加载商品统计数据
        // const dashboardStore = useDashboardStore()
        // dashboardStore.getGoodsAmountListAction()
      }
    }
  }
})

export default useLoginStore
